<?php

namespace app\award;

use app\controllers\h5\uni\HomeController;
use app\models\AdminSupplier;
use app\models\AwardList;
use app\models\AwardResult;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\Pool;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\user\UserScoreTicket;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Award
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;

    // 总金额
    protected $amount;

    protected $is_bao = false;
    protected $is_merchant = false;
    protected $is_buy = false;


    public function __construct(Order $order, $is_reset = false)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();

        $this->is_reset = $is_reset;

        $this->items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->amount = $this->order->total_pay - $this->order->total_freight;

        // 爆品
        $this->is_bao = ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT']);
        if ($this->is_bao) {
            $this->score();
            $this->bao();
            $this->pool();
        }

        // 线下商家
        $this->is_merchant = ProductAreaList::checkInArea($product_id, Product::$areaMap['MERCHANT']);
        if ($this->is_merchant) {
            $this->pool();
        }

        // 购物区
        $this->is_buy = ProductAreaList::checkInArea($product_id, Product::$areaMap['BUY']);
        if ($this->is_buy) {

        }

        // 线下扫码
        if ($order->pay_type == 121) {
            $this->pool();
            $this->scan();
        }
    }

    // 线下扫码返佣
    private function scan()
    {
        $discount = AdminSupplier::find()
            ->where(['id' => $this->order->supplier_id])
            ->select(['discount'])
            ->scalar();
        $discount /= 100;

        $total = $this->amount * $discount;

        // var_dump($total);exit;

        $name = '线下扫码';
        $type = 21;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $chain = Chain::getReferrerChain($this->user->id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
        ], true);

        // var_dump($chain);exit;

        foreach ($chain as $user) {
            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $commission = $total * $this->set->shop_vip1 / 100;
                $this->saveCommission($user->id, $commission, $type, $name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $commission = $total * $this->set->shop_vip2 / 100;
                $this->saveCommission($user->id, $commission, $type, $name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $commission = $total * $this->set->shop_vip3 / 100;
                $this->saveCommission($user->id, $commission, $type, $name);
                $has_vip3 = true;
                break;
            }

        }

        // $vip1 = Chain::getReferrerChain($this->user->id, [UserLevel::$keys['vip1']], true);
        // if ($vip1) {
        //     $vip1 = $vip1[0];
        //     $commission = $total * $this->set->shop_vip1 / 100;
        //     $this->saveCommission($vip1->id, $commission, 21, '线下扫码');
        //
        //     $vip2 = Chain::getReferrerChain($vip1->id, [UserLevel::$keys['vip2']], true);
        //     if ($vip2) {
        //         $vip2 = $vip2[0];
        //         $commission = $total * $this->set->shop_vip2 / 100;
        //         $this->saveCommission($vip2->id, $commission, 21, '线下扫码');
        //
        //         $vip3 = Chain::getReferrerChain($vip2->id, [UserLevel::$keys['vip3']], true);
        //         if ($vip3) {
        //             $vip3 = $vip3[0];
        //             $commission = $total * $this->set->shop_vip3 / 100;
        //             $this->saveCommission($vip3->id, $commission, 21, '线下扫码');
        //         }
        //     }
        // }
    }


    // 送积分
    private function score()
    {
        // 自己
        if ($this->amount >= $this->set->vip3) {
            $score = $this->set->vip3_score_self;
        } else if ($this->amount >= $this->set->vip1) {
            $score = $this->set->vip1_score_self;
        }
        $this->saveCommission($this->user->id, 0, 1, '下单送积分', $score, 1);

        // 推荐人
        $r = Chain::getReferrer($this->user->id, true);
        if ($r) {
            $score = 0;
            if ($r->level == UserLevel::$keys['vip3']) {
                $score = $this->set->vip3_score_1;
            } else if ($r->level == UserLevel::$keys['vip2']) {
                $score = $this->set->vip2_score_1;
            } else if ($r->level == UserLevel::$keys['vip1']) {
                $score = $this->set->vip1_score_1;
            }
            $this->saveCommission($r->id, 0, 2, '推荐送积分', $score, 1);

            $r2 = Chain::getReferrer($r->id, true);
            if ($r2) {
                $score = 0;
                if ($r2->level == UserLevel::$keys['vip3']) {
                    $score = $this->set->vip3_score_2;
                } else if ($r2->level == UserLevel::$keys['vip2']) {
                    $score = $this->set->vip2_score_2;
                } else if ($r2->level == UserLevel::$keys['vip1']) {
                    $score = $this->set->vip1_score_2;
                }
                $this->saveCommission($r2->id, 0, 3, '推荐送积分', $score, 1);
            }
        }
    }

    // 报单
    private function bao()
    {
        // todo 这里好象推的都是会员算法
        $r = Chain::getReferrer($this->user->id, true);
        if ($r) {
            $amount = 0;
            if ($r->level == UserLevel::$keys['vip3']) {
                $amount = $this->set->vip3_amount_1;
            } else if ($r->level == UserLevel::$keys['vip2']) {
                $amount = $this->set->vip2_amount_1;
            } else if ($r->level == UserLevel::$keys['vip1']) {
                $amount = $this->set->vip1_amount;
            }
            $this->saveCommission($r->id, $amount, 11, '直推');

            $r2 = Chain::getReferrer($r->id, true);
            if ($r2) {
                $amount = 0;
                if ($r2->level == UserLevel::$keys['vip3']) {
                    $amount = $this->set->vip3_amount_2;
                } else if ($r2->level == UserLevel::$keys['vip2']) {
                    $amount = $this->set->vip2_amount_2;
                }
                $this->saveCommission($r2->id, $amount, 12, '间推');
            }
        }
    }

    // 奖金池
    private function pool()
    {
        $pool = Pool::getLastOne();
        if ($this->order->supplier_id > 0) {

            $discount = AdminSupplier::find()
                ->where(['id' => $this->order->supplier_id])
                ->select(['discount'])
                ->scalar();
            $discount /= 100;

            $total = $this->amount * $discount;
        } else {
            // $total = $this->amount;
            $total = 0;
        }

        $total = $total * $this->set->pool / 100;

        // var_dump($discount, $total);exit;

        $pool->v1 += $total * $this->set->v1_ratio / 100;
        $pool->v2 += $total * $this->set->v2_ratio / 100;
        $pool->v3 += $total * $this->set->v3_ratio / 100;
        $pool->v4 += $total * $this->set->v4_ratio / 100;

        $pool->save();
    }

    // 保存佣金 (await balance)
    protected function saveCommission($user_id, $balance, $type, $name, $score = 0, $status = 1)
    {
        if ($balance >= 0.01 || $score >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = $status;
            $model->score = $score;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();
            $account = UserAccount::findOne(['user_id' => $user_id]);

            if ($account) {

                // 积分
                $account->score += $score;

                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }

              $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, '返佣', $this->order->id);
            }

            return true;
        }
    }

}